package com.uduemc.biso.node.web.api.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.common.entities.surfacedata.maindata.Logo;
import com.uduemc.biso.node.core.common.siteconfig.SiteMenuConfig;
import com.uduemc.biso.node.core.entities.HCompanyInfo;
import com.uduemc.biso.node.core.entities.HConfig;
import com.uduemc.biso.node.core.entities.HPersonalInfo;
import com.uduemc.biso.node.core.entities.SConfig;
import com.uduemc.biso.node.web.api.dto.RequestHostBaseInfo;
import com.uduemc.biso.node.web.api.dto.RequestLogoSave;
import com.uduemc.biso.node.web.api.service.HostService;
import com.uduemc.biso.node.web.api.service.LogoService;
import com.uduemc.biso.node.web.api.service.SConfigService;
import com.uduemc.biso.node.web.api.service.WebSiteService;

@RestController
@RequestMapping("/api/baseinfo")
public class BaseinfoController {

	private static final Logger logger = LoggerFactory.getLogger(HostController.class);

	@Autowired
	private HostService hostServiceImpl;

	@Autowired
	private LogoService logoServiceImpl;

	@Autowired
	private WebSiteService webSiteServiceImpl;

	@Autowired
	private SConfigService sConfigServiceImpl;

	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * 获取渲染数据
	 * 
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/render-info")
	public JsonResult infos() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Logo logo = logoServiceImpl.getCurrentRenderInfo();
		if (logo == null) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(logo);
	}

	/**
	 * 保存请求数据，并返回渲染数据
	 * 
	 * @param requestLogoSave
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/save-info")
	public JsonResult saveInfo(@RequestBody RequestLogoSave requestLogoSave)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Logo logo = logoServiceImpl.saveSiteLogo(requestLogoSave);
		if (logo == null) {
			return JsonResult.assistance();
		}
		webSiteServiceImpl.cacheCurrentSiteClear();
		return JsonResult.messageSuccess("更新成功！", logo);
	}

	/**
	 * 获取当前主机的基础信息，包含公司信息以及个体信息和经营类型
	 * 
	 * @param siteId
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/get-base-info")
	public JsonResult getBaseInfo()
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		HConfig currentHostConfig = hostServiceImpl.getCurrentHostConfig();
		HCompanyInfo currentHostCompanyInfo = hostServiceImpl.getCurrentHostCompanyInfo();
		HPersonalInfo currentHostPersonalInfo = hostServiceImpl.getCurrentHostPersonalInfo();

		Map<String, Object> mapResult = new HashMap<>();
		mapResult.put("config", currentHostConfig);
		mapResult.put("companyInfo", currentHostCompanyInfo);
		mapResult.put("personalInfo", currentHostPersonalInfo);
		return JsonResult.ok(mapResult);
	}

	/**
	 * 通过传入的参数 RequestHostBaseInfo 对其主机基础信息进行修改
	 * 
	 * @param requestHostBaseInfo
	 * @param errors
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/save-base-info")
	public JsonResult saveBaseInfo(@Valid @RequestBody RequestHostBaseInfo requestHostBaseInfo, BindingResult errors)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		logger.info("insert: " + requestHostBaseInfo.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}
			logger.error(message.toString());
			return JsonResult.illegal();
		}

		boolean bool = hostServiceImpl.updateCurrentBaseInfo(requestHostBaseInfo);
		if (!bool) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("更新成功！");
	}

	/**
	 * 获取当前站点的菜单配置
	 */
	@PostMapping("/update-site-menu-config")
	public JsonResult updateSiteMenuConfig(@Valid @RequestBody SiteMenuConfig siteMenuConfig)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		int maxIndex = siteMenuConfig.getMaxIndex();
		if (maxIndex < 0 || maxIndex > 2) {
			siteMenuConfig.setMaxIndex(2);
		}
		SConfig sConfig = sConfigServiceImpl.updateCurrentSiteMenuConfig(siteMenuConfig);
		if (sConfig == null) {
			return JsonResult.illegal();
		}
		try {
			siteMenuConfig = objectMapper.readValue(sConfig.getMenuConfig(), SiteMenuConfig.class);
		} catch (IOException e) {
		}
		webSiteServiceImpl.cacheCurrentSiteClear();
		return JsonResult.messageSuccess("修改成功！", siteMenuConfig);
	}
}
